import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:xiongan_app_yy/common/user_singleton.dart';
import 'package:xiongan_app_yy/entrys/rp/user_entity.dart';
import 'package:xiongan_app_yy/provider/message_provider.dart';
import 'package:xiongan_app_yy/provider/user_info.dart';
import 'package:xiongan_app_yy/net/internet_api.dart';
import 'package:xiongan_app_yy/provider/warehouse_info.dart';
import 'package:xiongan_app_yy/utils/md5_utils.dart';
import 'package:xiongan_app_yy/utils/sp_utils.dart';
import 'package:xiongan_app_yy/utils/version_utils.dart';
import 'comm/input_contr_widget.dart';

/**
 * UserHeaderImg Widget 登录界面头像Widget
 * @param headerIcon 用来头像图标
 * **/
class HeaderImgWidget extends StatelessWidget {
  final Icon headerIcon;
  HeaderImgWidget({this.headerIcon});


  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      alignment: Alignment.topCenter,
      margin: EdgeInsets.only(top: 80),
      child: Container(
        width: 100,
        height: 100,
        padding: EdgeInsets.all(8),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(120),
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                  color: Color.fromRGBO(0, 0, 0, .3),
                  offset: Offset(0, 0),
                  blurRadius: 10)
            ]),
        child: Container(
          decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(120),
              color: Color(0xffcccccc)),
          child: headerIcon,
        ),
      ),
    );
  }
}

/**
 * LoginFormWidget 登录界面Form widget
 * **/
class LoginFormWidget extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return LoginFormWidgetState();
  }

}

class LoginFormWidgetState extends State {
  TextEditingController account = TextEditingController();
  TextEditingController pwd = TextEditingController();
  Widget rIcon;
  String TYPE_KEY = "isAdmin";
  String ACCOUNT_NUMBER = "=accountNumber";
  String PASSWORD = "password";
  String REMEMBER = "remember";
  bool disabled=true;
  bool seeState=true;//图标状态
  bool passWordVisibility=true;//密码文字状态,true为密码圆点模式
  bool remember;

  saveType(bool str) {
    SpUtil.preferences.setBool(TYPE_KEY, str);
  }


  @override
  void initState() {
    remember=SpUtil.preferences.getBool(REMEMBER)??false;
    print(remember);
    if(remember){
      account.text=SpUtil.preferences.getString(ACCOUNT_NUMBER);
      pwd.text=SpUtil.preferences.getString(PASSWORD);
    }
  }

  @override
  Widget build(BuildContext context) {
    print("登录页build");

    if(seeState){
      rIcon=Icon(Icons.visibility, size: 28, color: Color(0XFFACD3EE));
    }else{
      rIcon=Icon(Icons.visibility_off, size: 28, color: Color(0XFFACD3EE));
    }
    return Container(
      margin: EdgeInsets.only(top: 60),
      width: double.infinity,
      alignment: Alignment.center,
      padding: EdgeInsets.only(left: 40, right: 40),
      child: Form(
        autovalidate: true,
        child: Column(
          children: <Widget>[
            InputContrWidget(
              hText: "请输入账号",
              isPassWord: false,
              LengthInputFormatters: 11,
              control: account,
              lIcon: Icon(Icons.person, size: 28, color: Color(0XFFACD3EE)),
            ),
            InputContrWidget(
              hText: "请输入密码",
              control: pwd,
              LengthInputFormatters: 16,
              valiFuns: (v){
                if(v.toString().length==0){
                  remember=false;
                }
              },
              onClick: (){
                if(remember){
                  this.setState(() {
                    Future.delayed(Duration(milliseconds: 500),(){
                        pwd.clear();
                    });
                  });
                }else{
                  setState(() {
                    seeState=!seeState;
                    passWordVisibility=!passWordVisibility;
                  });
                }

              },
              rIcon: rIcon,
              isPassWord: passWordVisibility,
              lIcon: Icon(Icons.lock, size: 28, color: Color(0XFFACD3EE)),
            ),
            Row(
              children: <Widget>[
                Expanded(
                    flex: 1,
                    child: Container(
                      margin: EdgeInsets.only(top: 40),
                      child: Center(
                        child: Center(
                          child: FlatButton(
                              color: Color(0xFF00A5F1),
                              textColor: Colors.white,
                              disabledColor: Colors.black26,
                              onPressed: disabled?() {
                                setState(() {
                                  disabled=false;
                                });
                                InternetAPI.getInstance().post(
                                  "WConfiguration/PptUser/LoginUser",
                                  (data) {
                                    SpUtil.preferences.setString(ACCOUNT_NUMBER,account.text);
                                    SpUtil.preferences.setString(PASSWORD,pwd.text);
                                    SpUtil.preferences.setBool(REMEMBER,true);
                                    UserEntity user = UserEntity.fromJson(data);
                                    DataSingleton().Data = user;
                                    saveType(user.isAdmin);
                                    if (user.imageurl == null) {
                                      Provider.of<UserInfo>(context)
                                          .set(user.username, "");
                                    } else {
                                      Provider.of<UserInfo>(context)
                                          .set(user.username, user.imageurl);
                                    }
                                    List<UserWarehouselist>warehouseListSelected = new List();
                                    List<UserWarehouselist> warehouseList = DataSingleton().Data.warehouseList;
                                    for (var i = 0; i < warehouseList.length; i++) {
                                      if (warehouseList.elementAt(i).selected == true) {
                                        warehouseListSelected.add(warehouseList.elementAt(i));
                                      }
                                    }
                                    if (warehouseListSelected.length > 0) {
                                      DataSingleton().warehouse = warehouseListSelected;//可选仓库集保存
                                      if (DataSingleton().Data.lastwarehouseid != null && DataSingleton().Data.lastwarehouseid.length > 0) {
                                        for (var i = 0; i < DataSingleton().warehouse.length; i++) {
                                          if (DataSingleton().warehouse.elementAt(i).id == DataSingleton().Data.lastwarehouseid) {
                                            DataSingleton().warehouseChoice = DataSingleton().warehouse.elementAt(i);
                                            print(DataSingleton().warehouseChoice.id);
                                          }
                                        }
                                      } else {
                                        DataSingleton().warehouseChoice = warehouseListSelected[0];
                                      }
                                      Provider.of<WarehouseInfo>(context).initMode(DataSingleton().warehouseChoice);
                                      setState(() {
                                        disabled=true;
                                        remember=true;
                                      });
                                      Navigator.pushNamed(context, "/home",arguments: user.appModuleMenusList);
                                    } else {
                                      //弹toast提示无仓库可操作
                                    }
                                  },errorCallBack: (err){
                                  setState(() {
                                    disabled=true;
                                  });
                                },
                                  params: {
                                    'useraccount': account.text,
                                    'password': md5Funs(pwd.text),
                                    "systemtype":"2",
                                    "AppCurrentversion":"1.1.0"
                                  },
                                );
                              }:null,
                              child: Text("登录"),
                              shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(10))),
                        ),
                      ),
                    ))
              ],
            )
          ],
        ),
      ),
    );
  }
}
